import LocalizedStrings from 'react-localization';
import { zh } from '../local/zh';
import { en } from '../local/en';
import { for_obj } from './base/util';

const local_string = new LocalizedStrings({
    zhcn: zh,
    enus: en,
});

const loc = (k) => local_string[k];

const loc_set_zh = () => local_string.setLanguage('zhcn');

const loc_set_en = () => local_string.setLanguage('enus');

const loc_lang = () => local_string.getLanguage();

const loc_lang_change = () => {
    const ret = loc_lang();
    if (ret === "zhcn") {
        loc_set_en();
    }
    else {
        loc_set_zh();
    }

    localStorage.setItem('meslang', ret);
};

/* hinit ret:
 * {
 *      zhcn: {
 *      },
 *      enus: {
 *      }
 * }
*/
const init_lang = (hinit=null) => {
    if (hinit) {
        const old = local_string.getContent();
        const tmp = hinit();

        for_obj(tmp, (k, v) => {
            if (old[k]) {
                for_obj(v, (sk, sv) => {
                    old[k][sk] = sv;
                });
            }
            else {
                old[k] = v;
            }
        });

        local_string.setContent(old);
    }

    const ret = localStorage.getItem('meslang');
    if (!ret) {
        return;
    }

    if (ret === "zhcn") {
        loc_set_en();
    }
    else {
        loc_set_zh();
    }
};

export {loc_set_en, loc_set_zh, loc_lang, loc, loc_lang_change, init_lang};
